package com.app.service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.util.StringUtils;
import com.app.common.TotalConfig;
import com.app.mapper.CompanyMapper;
import com.app.mapper.GasDetailsMapper;
import com.app.model.SysUser;
import com.app.pojo.Company;
import com.app.pojo.GasDetails;
import com.app.service.IGasDetailsService;
import com.app.service.ISysUserService;
import com.app.util.Result;
import com.app.vo.GasDetailsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 燃气详细信息 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2024-07-29
 */
@Service
public class GasDetailsServiceImpl extends ServiceImpl<GasDetailsMapper, GasDetails> implements IGasDetailsService {

    @Autowired
    private GasDetailsMapper gasDetailsMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private ISysUserService sysUserService;


    // 如果你需要执行批量插入，可以直接调用 saveBatch 方法
    public void batchInsert(List<GasDetails> list) {
        this.saveBatch(list);
    }

    @Override
    public GasDetailsVo getGasDetailsInfo(String account,String companyName) {
        QueryWrapper<GasDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account).eq("company_name", companyName);
        GasDetails gasDetails = gasDetailsMapper.selectOne(queryWrapper);

        GasDetailsVo gasDetailsVo = new GasDetailsVo();
        gasDetailsVo.setGasDetails(gasDetails);
        return gasDetailsVo;
    }

    @Override
    public GasDetailsVo getMyGasDetailsInfoList(Integer page, Integer limit, Integer userid) {
        Page<GasDetails> p =new Page(page,limit);
//        List<Map<String, Object>> list = gasDetailsMapper.getGasDetailsInfoList(p,userid);
        IPage<GasDetails> list = gasDetailsMapper.getGasDetailsInfoList(p,userid);
        GasDetailsVo gasDetailsVo = new GasDetailsVo();
        gasDetailsVo.setList(list.getRecords());
        gasDetailsVo.setCount((int) list.getTotal());
        return gasDetailsVo;
    }


    @Override
    public Map<String, Object> getSumGasDetailsInfo(String account,Integer userId) {
        Map<String, Object> sumGasDetailsInfo = gasDetailsMapper.selectSumMoneyAndGasTotal(account,userId);
        return sumGasDetailsInfo;
    }
    /**
     * Admin首页查询欠费用户数
     * @return
     */
    @Override
    public Integer countArrearsUserNum() {
         Integer countArrearsUserNum = gasDetailsMapper.countArrearsUserNum();
        return countArrearsUserNum;
    }




    /**
     * 列表查询
     * @return
     */
    @Override
    public Result<List<GasDetails>> listPersonnelInformation(Integer page, Integer limit, String keyword) {
        Page<GasDetails> page1 = new Page<>(page, limit);
        QueryWrapper<GasDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 所有查询都必须满足的条件

        // 如果keyword不为空，则构建OR条件
        if (StringUtils.isNotBlank(keyword)) { // 使用StringUtils或自定义的非空检查
            queryWrapper.nested(wrapper -> {
                wrapper.like("account", keyword)
                        .or().like("user_name", keyword) // 添加 user_name 字段的搜索
                        .or().like("user_phone", keyword)
                        .or().like("user_address", keyword) // 添加 address 字段的搜索
                        .or().like("gas_number", keyword);
            });
        }
        Page<GasDetails> selectPage = gasDetailsMapper.selectPage(page1, queryWrapper);
        GasDetailsVo gasDetailsVo = new GasDetailsVo();
        gasDetailsVo.setList(selectPage.getRecords());

        // 注意：这里可能会因为getTotal()返回long类型而丢失数据，如果数据量很大，请考虑使用long类型
        gasDetailsVo.setCount((int) selectPage.getTotal()); // 保留原样，但请考虑使用long类型以避免潜在的数据丢失
        return Result.success(gasDetailsVo);
    }

    @Override
    public Result deletePersonnelInformation(Integer id) {
        GasDetails gasDetails = new GasDetails();
        gasDetails.setId(id);
        gasDetails.setStatus(0);
        gasDetailsMapper.updateById(gasDetails);
        return Result.success("删除成功");
    }

    @Override
    public Result addAndUpdatePersonnelInformation(GasDetails gasDetails) {
        if (!StpUtil.hasPermission("admin:equipment:save")){
            return Result.error(TotalConfig.NO_PERMISSION);
        }
        SysUser sysUserById = sysUserService.getById(StpUtil.getLoginIdAsLong());
        if(gasDetails.getId()==null){//新增
            QueryWrapper<GasDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account",gasDetails.getAccount());
            queryWrapper.eq("gas_number",gasDetails.getUserName());
            List<GasDetails> personnelInformations = this.list(queryWrapper);
            if(personnelInformations.size()>0){
                return Result.error("用户信息已存在");
            }
            QueryWrapper<Company> queryWrapper2 = new QueryWrapper<>();
            List<Company> companies = companyMapper.selectList(queryWrapper2);
            String companyName = "";
            Integer companyId = null;
            BigDecimal companyUnitPrice = new BigDecimal(0);
            if (companies.size() >= 1) {
                companyName = companies.get(0).getCompanyName();
                companyId = companies.get(0).getId();
                companyUnitPrice = companies.get(0).getUnitPrice();
            }

            if (gasDetails.getBalance()==null ){
                gasDetails.setBalance(new BigDecimal(0));
            }
            gasDetails.setCompanyName(companyName);
            gasDetails.setCompanyId(companyId);
            gasDetails.setUnitPrice(companyUnitPrice);
            gasDetails.setStatus(1);
            gasDetails.setCreateTime(LocalDateTime.now());
            gasDetails.setCreateUser(sysUserById.getId());
            gasDetails.setValveStatus(0);
            gasDetails.setAccountOpeningStatus(0);
            gasDetailsMapper.insert(gasDetails);
            return Result.success("新增成功");
        }else {
            gasDetails.setUpdateTime(LocalDateTime.now());
            gasDetails.setUpdateUser(sysUserById.getId());
            gasDetailsMapper.updateById(gasDetails);
            return Result.success("修改成功");
        }
    }


}
